package com.mediacloud.app.newsmodule.fragment.baoliao.api;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.mediacloud.app.newsmodule.fragment.baoliao.model.CrmsUploadFileResult;
import com.mediacloud.app.newsmodule.fragment.baoliao.model.add.MulFileUpload;
import com.mediacloud.app.quanzi.model.FaBuDongTaiBean;
import com.mediacloud.app.reslib.BuildConfig;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.reslib.util.HTTPClient;
import com.mediacloud.app.user.net.SSLSocketClient;
import com.mediaclound.appfactnet.interceptor.SignInterceptor;
import com.mediaclound.appfactnet.utils.GETBadInterceptor;
import com.mediacloud.app.util.ProxyUtil;

import java.io.File;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.X509TrustManager;

import okhttp3.Dns;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
import retrofit2.http.PartMap;

/**
 * @author TXL
 * description :
 */
public class CrmsApi {

    private volatile static ISpiderCrmsApi crmsApi ;

    public static ISpiderCrmsApi getCrmsApi(Context context){
        if(crmsApi == null){
            synchronized (CrmsApi.class){
                if(crmsApi == null){
                    initCrmsApi(context.getApplicationContext());
                }
            }
        }
        return crmsApi;
    }

    /**
     * wifi环境下优先使用ipv4
     */
    public static class MyDns implements Dns {
        @Override
        public List lookup(String hostname) throws UnknownHostException {
            if (hostname == null){
                throw new UnknownHostException ("hostname == null") ;
            }else{
                try{
                    List inetAddressList = new ArrayList<>();
                    InetAddress[] inetAddresses = InetAddress.getAllByName (hostname) ;
                    for (InetAddress inetAddress: inetAddresses){
                        if (inetAddress instanceof Inet4Address){
                            inetAddressList.add(0, inetAddress) ;
                        }else{
                            inetAddressList.add(inetAddress);
                        }
                    }
                    return inetAddressList;
                }catch (NullPointerException var4){
                    UnknownHostException unknownHostException = new UnknownHostException("Broken system behavior");
                    unknownHostException.initCause(var4);
                    throw unknownHostException;
                }
            }
        }
    }

    private static void initCrmsApi(Context context){
        String baseUrl = AppFactoryGlobalConfig.getAppServerConfigInfo(context).crms;
        if(TextUtils.isEmpty(baseUrl)){
            Log.e("DataInvokeUtil","initCrmsApi failed spider_cms is null");
            return;
        }
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.addInterceptor(new SignInterceptor());
        builder.addInterceptor(new GETBadInterceptor(AppFactoryGlobalConfig.getAppServerConfigInfo(context).crms,AppFactoryGlobalConfig.getAppServerConfigInfo(context).cdn_crms));
        builder.dns(new MyDns());
        if(BuildConfig.DEBUG) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
            builder.addInterceptor(loggingInterceptor);
        }
        builder.protocols(Collections.unmodifiableList(Arrays.asList(Protocol.HTTP_1_1, Protocol.HTTP_2)));
        builder.sslSocketFactory(SSLSocketClient.getSSLSocketFactory(), (X509TrustManager) SSLSocketClient.getTrustManager()[0]);
        builder.hostnameVerifier(SSLSocketClient.getHostnameVerifier());
        builder.readTimeout(HTTPClient.TIME_OUT, TimeUnit.SECONDS);
        builder.connectTimeout(HTTPClient.TIME_OUT, TimeUnit.SECONDS);
        ProxyUtil.config(builder);
        builder.addInterceptor(chain -> {
            Request original = chain.request();
            Request request = original.newBuilder()
                    .header("tenantId", context.getResources().getString(com.mediacloud.app.reslib.R.string.tenantid))
                    .build();
            return chain.proceed(request);
        });

        Retrofit retrofit = new Retrofit.Builder().baseUrl(baseUrl+"/")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(builder.build())
                .build();
        crmsApi = retrofit.create(ISpiderCrmsApi.class);
    }
    public static List<MultipartBody.Part> filesToMultipartBodyPartsV2(Map<FaBuDongTaiBean, File> files, Map<FaBuDongTaiBean,ProgressRequestBody.UploadCallbacks> callbacks) {
        List<MultipartBody.Part> parts = new ArrayList<>(files.size());
        files.entrySet();
        ProgressRequestBody.UploadCallbacks callback;
        for(Map.Entry<FaBuDongTaiBean,File> entry: files.entrySet())
        {
            MediaType mediaType=null;
            if (PictureMimeType.getMimeType(entry.getKey().getLocalMedia().getMimeType()) == PictureConfig.TYPE_IMAGE){
                mediaType=MediaType.parse("image/png");
            }else if (PictureMimeType.getMimeType(entry.getKey().getLocalMedia().getMimeType()) == PictureConfig.TYPE_VIDEO){
                mediaType=MediaType.parse("video/*");
            }else{
                mediaType=MediaType.parse("*/*");
            }
            callback = callbacks.get(entry.getKey());
            ProgressRequestBody progressRequestBody =
                    new ProgressRequestBody(entry.getValue(),mediaType,entry.getValue().getName(),callback);
            MultipartBody.Part part = MultipartBody.Part.createFormData("file", entry.getValue().getName(), progressRequestBody);
            parts.add(part);
        }
        return parts;
    }

    public static List<MultipartBody.Part> filesToMultipartBodyParts(Map<LocalMedia, File> files, Map<LocalMedia,ProgressRequestBody.UploadCallbacks> callbacks) {
        List<MultipartBody.Part> parts = new ArrayList<>(files.size());
        files.entrySet();
        ProgressRequestBody.UploadCallbacks callback;
        for(Map.Entry<LocalMedia,File> entry: files.entrySet())
        {
            MediaType mediaType=null;
            if (PictureMimeType.getMimeType(entry.getKey().getMimeType()) == PictureConfig.TYPE_IMAGE){
                mediaType=MediaType.parse("image/png");
            }else if (PictureMimeType.getMimeType(entry.getKey().getMimeType()) == PictureConfig.TYPE_VIDEO){
                mediaType=MediaType.parse("video/*");
            }else{
                mediaType=MediaType.parse("*/*");
            }
            callback = callbacks.get(entry.getKey());
            ProgressRequestBody progressRequestBody =
                    new ProgressRequestBody(entry.getValue(),mediaType,entry.getValue().getName(),callback);
            MultipartBody.Part part = MultipartBody.Part.createFormData("file", entry.getValue().getName(), progressRequestBody);
            parts.add(part);
        }
        return parts;
    }
    public static RequestBody convertToRequestBody(String param) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), param);
        return requestBody;
    }
    public interface ISpiderCrmsApi {

        @Multipart
        @POST("client/productMainResource/mulFileUpload")
        Call<CrmsUploadFileResult> uploadFiles(@PartMap Map<String, RequestBody> map,
                                               @Part List<MultipartBody.Part> parts);


        /**
         * 多文件上传
         */
        @Multipart
        @POST("api/productMainResource/mulFileUpload")
        Call<MulFileUpload> mulFileUpload(@PartMap Map<String, RequestBody> map, @Part List<MultipartBody.Part> file);


        /**
         * 爆料视频上传
         */
        @Multipart
        @POST("api/productMainResource/mulFileUpload")
        Call<MulFileUpload> revealFileUpload(@PartMap Map<String, RequestBody> map, @Part List<MultipartBody.Part> file);

    }
}